import { ControlValueAccessor } from '@angular/forms';
import { Input } from '@angular/core';

export abstract class ValueAccessorBase<T> implements ControlValueAccessor {
  private innerValue: T;

  private changed: Array<(value: T) => void> = [];
  private touched: Array<() => void> = [];

  get value(): T {
    // console.log('get value ');
    return this.innerValue;
  }

  set value(value: T) {
    // console.log('set value ', value);
    if (this.innerValue !== value) {
      this.innerValue = value;
      this.changed.forEach(f => f(value));
    }
  }

  writeValue(value: T) {
    // console.log('write value ', value);
    this.value = value;
  }

  registerOnChange(fn: (value: T) => void) {
    // console.log('register onChange ');
    this.changed.push(fn);
  }

  registerOnTouched(fn: () => void) {
    // console.log('register onTouch ');
    this.touched.push(fn);
  }

  touch() {
    // console.log('touch ');
    this.touched.forEach(f => f());
  }
}
